import React, { useEffect, useCallback } from 'react';

export interface FontStyleProviderProps {
  children?: React.ReactNode;
}

/**
 * 中文字体样式提供器
 * 负责注入中文字体样式，处理不同系统的字体兼容性
 */
export const FontStyleProvider: React.FC<FontStyleProviderProps> = ({ children }) => {
  
  /**
   * 检测系统类型
   */
  const detectSystem = useCallback(() => {
    const userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.includes('mac')) return 'macos';
    if (userAgent.includes('win')) return 'windows';
    if (userAgent.includes('linux')) return 'linux';
    return 'unknown';
  }, []);

  /**
   * 检测字体是否可用
   */
  const checkFontAvailability = useCallback((fontFamily: string): boolean => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    if (!context) return false;

    const testText = '中文测试';
    const fallbackFont = 'monospace';
    
    // 设置回退字体并测量文本宽度
    context.font = `12px ${fallbackFont}`;
    const fallbackWidth = context.measureText(testText).width;
    
    // 设置目标字体并测量文本宽度
    context.font = `12px ${fontFamily}, ${fallbackFont}`;
    const targetWidth = context.measureText(testText).width;
    
    // 如果宽度不同，说明字体可用
    return targetWidth !== fallbackWidth;
  }, []);

  /**
   * 获取系统优化的字体栈
   */
  const getSystemOptimizedFontStack = useCallback(() => {
    const system = detectSystem();
    const baseFonts = [
      'system-ui',
      '-apple-system',
      'BlinkMacSystemFont'
    ];

    const chineseFonts = {
      macos: [
        '"PingFang SC"',
        '"PingFang TC"', 
        '"Hiragino Sans GB"',
        '"STHeiti Light"'
      ],
      windows: [
        '"Microsoft YaHei"',
        '"Microsoft JhengHei"',
        '"SimSun"',
        '"SimHei"'
      ],
      linux: [
        '"Source Han Sans SC"',
        '"Noto Sans CJK SC"',
        '"WenQuanYi Micro Hei"',
        '"Droid Sans Fallback"'
      ],
      unknown: [
        '"Source Han Sans SC"',
        '"Noto Sans CJK SC"',
        '"SimSun"'
      ]
    };

    const monoFonts = {
      macos: [
        '"SF Mono"',
        'Monaco'
      ],
      windows: [
        '"Cascadia Code"',
        'Consolas'
      ],
      linux: [
        '"Source Code Pro"',
        '"Liberation Mono"'
      ],
      unknown: [
        '"Courier New"'
      ]
    };

    const systemChineseFonts = chineseFonts[system] || chineseFonts.unknown;
    const systemMonoFonts = monoFonts[system] || monoFonts.unknown;

    const sansSerifStack = [
      ...baseFonts,
      ...systemChineseFonts,
      'sans-serif'
    ].join(', ');

    const monospaceStack = [
      ...systemMonoFonts,
      ...systemChineseFonts,
      'monospace'
    ].join(', ');

    return {
      sansSerif: sansSerifStack,
      monospace: monospaceStack
    };
  }, [detectSystem, checkFontAvailability]);

  /**
   * 注入字体样式
   */
  const injectFontStyles = useCallback(() => {
    const styleId = 'eko-chinese-font-styles';
    
    // 移除已有样式
    const existingStyle = document.getElementById(styleId);
    if (existingStyle) {
      existingStyle.remove();
    }

    const fontStacks = getSystemOptimizedFontStack();
    
    const styles = `
      /* Eko Extension 中文字体优化样式 */
      :root {
        --eko-font-family-chinese: ${fontStacks.sansSerif};
        --eko-font-family-mono: ${fontStacks.monospace};
        --eko-font-size-xs: 12px;
        --eko-font-size-sm: 14px;
        --eko-font-size-base: 16px;
        --eko-font-size-lg: 18px;
        --eko-line-height-base: 1.5;
        --eko-line-height-tight: 1.25;
      }

      /* 全局字体应用 */
      body, html, #root, .ant-app {
        font-family: var(--eko-font-family-chinese) !important;
        font-variant-east-asian: normal;
        text-rendering: optimizeLegibility;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        font-feature-settings: "kern" 1, "liga" 1;
      }

      /* Ant Design 组件字体优化 */
      .ant-input, 
      .ant-select, 
      .ant-textarea, 
      .ant-btn, 
      .ant-card, 
      .ant-form-item-label,
      .ant-form-item,
      .ant-card-head-title,
      .ant-alert,
      .ant-message,
      .ant-notification,
      .ant-modal,
      .ant-dropdown-menu,
      .ant-tooltip {
        font-family: var(--eko-font-family-chinese) !important;
      }

      /* 等宽字体区域 */
      .log-container, 
      pre, 
      code,
      .ant-typography-caption {
        font-family: var(--eko-font-family-mono) !important;
        font-feature-settings: "tnum" 1;
      }

      /* 强制覆盖内联样式 */
      [style*="font-family"] {
        font-family: var(--eko-font-family-chinese) !important;
      }

      /* 等宽字体区域强制覆盖 */
      pre[style*="font-family"],
      code[style*="font-family"],
      .log-container[style*="font-family"] {
        font-family: var(--eko-font-family-mono) !important;
      }

      /* 输入框中文优化 */
      input::placeholder,
      textarea::placeholder {
        font-family: var(--eko-font-family-chinese) !important;
        opacity: 0.65;
      }

      /* 按钮文字优化 */
      .ant-btn {
        font-weight: 400;
        letter-spacing: 0.02em;
      }

      /* 中文字符特殊处理 */
      .chinese-text {
        font-variant-east-asian: normal;
        font-feature-settings: "kern" 1, "liga" 1;
        text-rendering: optimizeLegibility;
      }
    `;

    const styleElement = document.createElement('style');
    styleElement.id = styleId;
    styleElement.textContent = styles;
    document.head.appendChild(styleElement);

    console.log('🎨 Eko Extension: 中文字体样式已注入', {
      system: detectSystem(),
      fontStacks
    });
  }, [getSystemOptimizedFontStack, detectSystem]);

  /**
   * 字体加载错误处理
   */
  const handleFontError = useCallback((error: Error) => {
    console.warn('⚠️ Eko Extension: 字体加载失败，使用系统默认字体', error);
    
    // 设置紧急回退方案
    const emergencyStyle = document.createElement('style');
    emergencyStyle.textContent = `
      body, html, #root, .ant-app {
        font-family: system-ui, sans-serif !important;
      }
      pre, code, .log-container {
        font-family: monospace !important;
      }
    `;
    document.head.appendChild(emergencyStyle);
  }, []);

  /**
   * 验证中文字符支持
   */
  const verifyChineseSupport = useCallback(() => {
    try {
      const testElement = document.createElement('div');
      testElement.style.cssText = `
        position: absolute;
        left: -9999px;
        top: -9999px;
        font-family: var(--eko-font-family-chinese);
        font-size: 16px;
      `;
      testElement.textContent = '中文测试字符';
      document.body.appendChild(testElement);
      
      const rect = testElement.getBoundingClientRect();
      const hasContent = rect.width > 0 && rect.height > 0;
      
      document.body.removeChild(testElement);
      
      if (!hasContent) {
        console.warn('⚠️ Eko Extension: 中文字符渲染可能存在问题');
        return false;
      }
      
      return true;
    } catch (error) {
      console.error('❌ Eko Extension: 中文字符支持验证失败', error);
      return false;
    }
  }, []);

  useEffect(() => {
    try {
      // 延迟注入样式，确保DOM准备就绪
      const timer = setTimeout(() => {
        injectFontStyles();
        
        // 验证中文字符支持
        setTimeout(() => {
          verifyChineseSupport();
        }, 100);
      }, 0);

      return () => {
        clearTimeout(timer);
      };
    } catch (error) {
      handleFontError(error as Error);
    }
  }, [injectFontStyles, verifyChineseSupport, handleFontError]);

  // 监听DOM变化，确保动态内容也能应用字体样式
  useEffect(() => {
    const observer = new MutationObserver((mutations) => {
      let shouldReapply = false;
      
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              shouldReapply = true;
            }
          });
        }
      });
      
      if (shouldReapply) {
        // 延迟重新应用样式，避免频繁操作
        setTimeout(() => {
          const chineseElements = document.querySelectorAll('*');
          chineseElements.forEach((element) => {
            const htmlElement = element as HTMLElement;
            if (htmlElement.textContent && /[\u4e00-\u9fff]/.test(htmlElement.textContent)) {
              htmlElement.classList.add('chinese-text');
            }
          });
        }, 50);
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });

    return () => {
      observer.disconnect();
    };
  }, []);

  return <>{children}</>;
};

export default FontStyleProvider;